<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { detailFormSchema } from './data';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const { SpuModule } = mcApi;
  const { QuotationApi } = SpuModule;

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 150,
    schemas: detailFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const ifUpdate = ref<boolean>(false);
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    await resetFields();
    ifUpdate.value = !!data.ifUpdate;
    setModalProps({
      minHeight: 50,
      confirmLoading: false,
      title: `${ifUpdate.value ? '编辑' : '新增'}阶梯报价条目`,
    });
    const { record } = data;
    await setFieldsValue({
      ...(record || {}),
      ladderQuotationListId: data.ladderQuotationListId,
    });
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      const values: any = await validate();
      setModalProps({ confirmLoading: true });
      const fun = unref(ifUpdate)
        ? QuotationApi.updateLadderQuotationListItem
        : QuotationApi.createLadderQuotationListItem;
      await fun(values);
      createMessage.success(`${unref(ifUpdate) ? '编辑' : '新增'}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less"></style>
